import request from '@/utils/request'

export function dialogueSend(params) {
    return request({
        url: '/tool/ai/dialogue',
        method: 'POST',
        data: params
    })
}
export function dialogueStreamSend(params) {
    const { prompt, onMessage, onReasoning,onRecommended, onError, onClose } = params;
    // 创建AbortController实例
    const controller = new AbortController();
    const signal = controller.signal;
    const fetchStream = async () => {
        try {
            const response = await fetch('/api/tool/ai/stream-dialogue', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(prompt),
                signal // 将signal传给fetch
            });
            if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
            }
            const reader = response.body.getReader();
            const decoder = new TextDecoder('utf-8');
            while (true) {         
                const { done, value } = await reader.read();
                if (done) {
                    if (onClose) onClose();
                    break;
                }
                const chunk = decoder.decode(value, { stream: true });
                const lines = chunk.split('\n');
                let jsonData = '';
                lines.forEach(line => {
                    if (line.includes('type')) {
                        jsonData = line.replace(/^data:/, "").trim(); // 去掉 "data: " 前缀并修剪空格
                        // 如果jsonData为空，跳过解析
                        if (!jsonData) {
                            return;
                        }
                        const data = JSON.parse(jsonData)
                        if(data.type == 'think'){
                            onReasoning(data.content)
                        }
                        if(data.type == 'text'){
                            onMessage(data.content)
                        }
                        if(data.type == 'recommended'){
                            onRecommended(data.content)
                        }
                    }
                });
            }
        } catch (err) {
            if(err.name != 'AbortError'){
                onError(err)
            }   
        }
    };

    // 开始请求
    fetchStream();

    // 返回一个对象，提供close方法用于中止请求
    return {
        close: () => {
            controller.abort();
            if (onClose) onClose();
        }
    };
}